import os
import py_compile
import shutil

exclude_files = ["__init__.py"]                     # 不需要编译py文件
exclude_dirs = ["__pycache__"]                      # 不需要遍历的目录
include_dirs = ["measurement", "utils", "tools"]    # 需要遍历的目录

def compile_py_files(directory):
    for root, dirs, files in os.walk(directory):
        # 仅处理指定根目录下的子目录
        relative_path = os.path.relpath(root, directory)
        if relative_path not in include_dirs:
            continue
        # 添加include_dirs初始值的所有子目录到include_dirs，实现递归遍历
        if '/' not in relative_path and '\\' not in relative_path: 
            for subdir in dirs:
                if subdir not in exclude_dirs:
                    include_dirs.append(os.path.join(relative_path, subdir))

        # 测试
        # print(root)
        # print(dirs)
        # print(relative_path)
        # print(files)
        # continue

        target_path = os.path.join(target_directory, relative_path)
        os.makedirs(target_path, exist_ok=True)

        for file in files:
            # 排除指定名称文件
            if file.endswith('.py') and file not in exclude_files:
                py_file = os.path.join(root, file)
                pyc_file = py_file + 'c'
                
                # 编译成 .pyc 文件
                try:
                    py_compile.compile(py_file, cfile=pyc_file, doraise=True)
                except py_compile.PyCompileError as e:
                    print(f"编译错误: {e}")
                    continue
                
                # 移动 .pyc 文件到目标目录
                shutil.move(pyc_file, os.path.join(target_path, file + 'c'))
                print(f"移动文件: {pyc_file} -> {os.path.join(target_path, file + 'c')}")

# 指定目录
source_directory = 'D:/GBfiles/mycode/Workspace/MeasurementProject/measurement_python'
# 编译后的代码目录（同目录结构存放）
target_directory = 'D:/GBfiles/mycode/Workspace/MeasurementProject/measurement_python_compiled'

# 调用函数编译并替换 .py 文件
compile_py_files(source_directory)
